package Threads;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;

public class ThreadPool {
    public static void main(String[] args) {

        // 创建线程池
        ExecutorService service = Executors.newFixedThreadPool(10);

        // ☆ 配置线程池，通过强制转换为ThreadPoolExecutor对象，可以设置线程池的属性
        ThreadPoolExecutor poolExecutor = (ThreadPoolExecutor) service;
        poolExecutor.setCorePoolSize(5);
        poolExecutor.setMaximumPoolSize(10);
        poolExecutor.setKeepAliveTime(1000, java.util.concurrent.TimeUnit.MILLISECONDS);

        // 创建Runnable接口实现类的实例
        Runnable sumDouble = new SumDoubleThread();
        Runnable sumSingle = new SumSingleThread();

        // 线程池execute方法用于执行Runnable任务
        service.execute(sumDouble);
        service.execute(sumSingle);

        // 关闭线程池
        service.shutdown();

    }
}

class SumDoubleThread implements Runnable {

    @Override
    public void run() {
        int sum = 0;
        for (int i = 0; i < 100; i++) {
            System.out.println(Thread.currentThread().getName() + "  Task: SumDoubleThread" + " -> " + i);
            if (i % 2 == 0)
                sum += i;
        }
        System.out.println(Thread.currentThread().getName() + "  Task: SumDoubleThread" + " sum = " + sum);
    }
}

class SumSingleThread implements Runnable {

    @Override
    public void run() {
        int sum = 0;
        for (int i = 0; i < 100; i++) {
            System.out.println(Thread.currentThread().getName() + "  Task: SumSingleThread" + " -> " + i);
            if (i % 2 != 0)
                sum += i;
        }
        System.out.println(Thread.currentThread().getName() + "  Task: SumSingleThread" + " sum = " + sum);
    }
}
